<template>
    <div class="system_setting">
        <!-- 系统状态 -->
        <div class="system_status">
            <header>{{ $t("setting.state") }}</header>
            <main>
                <aside>
                    <!-- cpu可视化 -->
                    <div class="title">{{ $t("system.cpu_usage") }}</div>
                    <div class="system_chart" ref="cpuRef">
                    </div>
                    <p class="desc">{{cpuCount}}
                        {{ $t("system.Core") }}
                    </p>
                    <!-- 详细信息 -->
                    <div class="detailInfo">
                        <p class="detail_header">
                            {{ $t("system.cpu_desc") }}
                            <el-tag type="success">
                                {{ $t("system.occupy") }}
                                {{ cpuUsage }}%</el-tag>
                        </p>
                        <p class="base_info">
                            {{ $t("system.base_info") }}
                        </p>
                        <ul style="list-style: none;">
                            <li style="padding: 10px 0;">
                                {{ $t("system.processor") }}
                                {{ platform}}</li>
                            <li>
                                {{ $t("system.core_num") }}
                                {{ cpuCount }}</li>
                        </ul>
                    </div>
                </aside>
                <aside>
                    <div class="title">{{ $t("system.mem_usage") }}</div>
                    <!-- 内存可视化 -->
                    <div class="system_chart" ref="memRef"></div>
                    <p class="desc">
                        <span>{{ freeMem }}</span> /
                        <span>{{ totalMem }}GB</span>
                    </p>
                            <!-- 详细信息 -->
                            <div class="detailInfo">
                        <p class="detail_header">
                            {{$t("system.mem_desc")}}
                            <el-tag type="success">
                                {{ $t("system.occupy") }}{{ memUsage }}%</el-tag>
                        </p>
                        <p class="base_info">
                            {{ $t("system.mem_info") }}
                        </p>
                        <ul class="aboutMem">
                            <li>
                                {{$t("system.usable")}}
                                 {{ freeMem }} GB</li>
                            <li>
                                {{$t("system.used")}}
                                {{ leftMem }} GB</li>
                            <li>
                                {{$t("system.total_mem")}}
                                {{ totalMem }} GB</li>
                            <li>
                                {{$t("system.shared")}}
                                 GB</li>
                        </ul>
                    </div>
                </aside>
                <aside>
                    <div class="title">{{ $t("system.system_path") }}</div>
                    <!-- 磁盘可视化 -->
                    <div class="system_chart" ref="diskRef"></div>
                    <p class="desc">
                        <span>{{ freeDisk }}</span> /
                        <span>{{ totalDisk }} GB</span>
                    </p>
                            <!-- 详细信息 -->
                    <div class="detailInfo">
                        <p class="detail_header">
                            {{ $t("system.disk_desc") }}
                            <el-tag type="success">{{ $t("system.occupy") }}{{ diskUsage }}%</el-tag>
                        </p>
                        <p class="base_info">
                            {{ $t("system.base_info") }}
                        </p>
                        <ul style="list-style: none;">
                            <li>
                                {{$t("setting.location")}}
                                 {{ systemInfo.diskInfo.currentPath}}</li>
                            <li style="margin-top: 10px;">
                                <span>
                                    {{ $t("system.total") }} 
                                    {{totalDisk}} GB</span>
                                <span>
                                    {{ $t("system.usable") }}
                                    {{freeDisk}} GB</span>
                                <span>
                                    {{ $t("system.used") }}
                                    {{leftDisk}} GB</span>
                            </li>
                        </ul>
                    </div>
                </aside>
            </main>
        </div>
        <!-- 系统设置 -->
        <div class="setting_parmas">
            <header>{{ $t("setting.setting") }}</header>
            <main>
                <section>
                    <span class="label">{{ $t("setting.title") }}</span>
                    <el-input v-model="system_title"/>
                    <el-button type="success" @click="changeSystemTitle">{{ $t("setting.save") }}</el-button>
                    <p class="desc">{{ $t("setting.title_desc") }}</p>
                </section>
                <section>
                    <span class="label">{{ $t("setting.username") }}</span>
                    <el-input v-model="userInfo.username" disabled/>
                    <el-button type="success" @click="validateUserCard('user')">{{ $t("setting.set") }}</el-button>
                    <p class="desc">{{ $t("setting.username_desc") }}</p>
                </section>
                <section>
                    <span class="label">{{ $t("setting.password") }}</span>
                    <el-input v-model="userInfo.password" type="password" disabled/>
                    <el-button type="success" @click="validateUserCard('pass')">{{ $t("setting.set") }}</el-button>
                    <p class="desc">{{ $t("setting.password_desc") }}</p>
                </section>
                <section>
                    <span class="label">{{ $t("setting.location") }}</span>
                    <el-input v-model="systemInfo.diskInfo.currentPath" type="text" disabled/>
                    <el-button type="success" @click="openFile">{{ $t("message.query") }}</el-button>
                    <p class="desc">{{ $t("setting.location_desc") }}</p>
                </section>
                <section>
                    <span class="label">{{ $t("setting.email") }}</span>
                    <el-input v-model="userInfo.email" type="text" disabled/>
                    <el-button type="success" v-if="!userInfo.email" @click="bindEmailFn">{{ $t("setting.bind") }}</el-button>
                    <el-button v-else @click="unbindEmailFn">{{ $t("setting.unbind") }}</el-button>
                    <p class="desc">{{ $t("setting.email_desc") }}</p>
                </section>
            </main>
        </div>
    </div>
 <!-- 系统设置用户名对话框 -->
    <el-dialog
        v-model="system_set_user_dialog"
        :title="$t('setting.update_username')"
        draggable
        width="350"
        align-center
        @close="resetUserInfo"
    >
    <el-form ref="updateUserRef" :rules="updateUserRule" :model="updateUsername">
           <!-- 用户名 -->
        <el-form-item prop="username" :label="$t('setting.u')" label-width="70px">
                <el-input
                    style="height: 40px;"
                    v-model="updateUsername.username"
                    class="w-50 m-2"
                    :placeholder="$t('setting.u')"
                >
            </el-input>
        </el-form-item>
        <el-form-item label="$t('setting.repeat')" label-width="70px">
          <el-input
            style="height: 40px;"
            v-model="updateUsername.repeat_username"
            class="w-50 m-2"
            :placeholder="$t('setting.repeat_enter')"
        >
    </el-input>
        </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="system_set_user_dialog = false">{{$t("message.cancel")}}</el-button>
        <el-button type="primary" @click="confirmUpdateUser">
          {{$t("message.confirm")}}
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 系统设置 -->
  <el-dialog
    v-model="system_set_Pass_dialog"
    :title="$t('setting.update_password')"
    draggable
    width="350"
    align-center
    @close="resetPassInfo"
  >
  <el-form :model="updateUserPass" :rules="updatePassRule" ref="updatePassRef">
    <el-form-item prop="password" lable-width="70px" :label="$t('setting.p')">
          <el-input
            style="height: 40px;"
            v-model="updateUserPass.password"
            class="w-50 m-2"
            type="text"
            :placeholder="$t('setting.password')"
      >
    </el-input>
        </el-form-item>
        <el-form-item lable-width="70px" :label="$t('setting.repeat')">
          <el-input
            style="height: 40px;"
            v-model="updateUserPass.repeat_password"
            class="w-50 m-2"
            type="password"
            placeholder="$t('setting.repeat')"
      >
    </el-input>
        </el-form-item>
  </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="system_set_Pass_dialog = false">{{$t("message.cancel")}}</el-button>
        <el-button type="primary" @click="confirmUpdatePass">
          {{$t("message.confirm")}}
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 绑定邮箱 -->
  <el-dialog 
    v-model="emailVisible" 
    :title="$t('setting.email')"
    width="350"
    draggable
    @close="resetEmail"
   >
    <el-form :rules="bindEmailRule" ref="bindEmailRef" :model="bindEmailModel">
        <el-form-item prop="email" :label="$t('setting.e')" label-width="70px">
            <el-input v-model="bindEmailModel.email"></el-input>
        </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="emailVisible = false">{{ $t("message.cancel") }}</el-button>
        <el-button type="primary" @click="confirmBindEmail">
          {{ $t("message.confirm") }}
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 验证用户的身份 -->
  <el-dialog
    v-model="validUserInfo"
    :title="$t('setting.valid')"
    width="350"
    draggable
    @close="handleClose"
  >
    <el-input type="password" v-model="adminUser_pass"></el-input>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="validUserInfo = false">{{$t("message.cancel")}}</el-button>
        <el-button type="primary" @click="validate_is_admin">
          {{$t("message.confirm")}}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
    import type { FormInstance, FormRules } from 'element-plus'
    import { onMounted,onUnmounted,ref,reactive,getCurrentInstance } from 'vue';
    import * as echarts from 'echarts'
    import {systemInfoPie} from '../../until/chart'
     import { moduleStore } from '../../store/module'
     import { adminStore } from '../../store/admin';
     let admin_store = adminStore()
     let {system_title} = storeToRefs(admin_store)
    import { storeToRefs } from 'pinia'
     let module_store = moduleStore()
     let {systemInfo} = storeToRefs(module_store)
     import { userStore } from '../../store/user';
     let user_store = userStore()
     let {userInfo,localWebsocket} = storeToRefs(user_store)
     let {proxy} = getCurrentInstance()
     // 系统参数：磁盘disk、内存mem、cpu
     let diskRef = ref()
    let memRef = ref()
    let cpuRef = ref()
    let diskPirture = reactive(null)
    let memPirture = reactive(null)
    let cpuPirture = reactive(null)
    let cpuCount = ref(0) // 内核数
    let freeMem = ref<string>("") // 可用内存
    let totalMem = ref<string>("") // 总共内存数
    let freeDisk = ref<string>("") // 可用磁盘
    let totalDisk = ref<string>("") // 总共磁盘
    let leftDisk = ref<string>("") // 剩余磁盘
    let cpuUsage = ref<string>("") // cpu占用率
    let platform = ref<string>("") // cpu平台
    let diskUsage = ref<string>("") // 磁盘占用率
    let memUsage = ref<string>("") // 内存占用率
    let leftMem = ref<string>("") // 已经用了内存
    onMounted(() => {
        diskPirture = echarts.init(diskRef.value)
        memPirture = echarts.init(memRef.value)
        cpuPirture = echarts.init(cpuRef.value)
        cpuCount.value = systemInfo.value.cpuInfo.cpuCount //获取内核数
        freeMem.value = (Number(systemInfo.value.memInfo.freeMem)/1024).toFixed(2)
        totalMem.value = (Number(systemInfo.value.memInfo.totalMem)/1024).toFixed(2)
        freeDisk.value = systemInfo.value.diskInfo.free // 可用磁盘
        totalDisk.value = systemInfo.value.diskInfo.size // 总共磁盘
        leftDisk.value = (totalDisk.value - freeDisk.value).toFixed(2) // 剩余磁盘
        platform.value = systemInfo.value.cpuInfo.platform // 处理器
        diskUsage.value = systemInfo.value.diskInfo.diskUsage // 磁盘占用率
        memUsage.value = systemInfo.value.memInfo.freememPercentage // 内存占用率
        freeMem.value = systemInfo.value.memInfo.freeMem // 剩余内存
        totalMem.value = systemInfo.value.memInfo.totalMem // 总内存
        leftMem.value = (totalMem.value - freeMem.value).toFixed(2)  //已经使用的内存
        // 渲染磁盘
        renderDisk()
        // 渲染cpu信息
        renderCpu()
        // 渲染内存信息
        renderMem()

        window.onresize = function() {
            setTimeout(() => {
                diskPirture.resize()
                memPirture.resize()
                cpuPirture.resize()
            },300)
        }
       
        // 磁盘的移动事件事件
        cpuRef.value.addEventListener("mouseenter",() => {
            let ele:HTMLElement = document.querySelectorAll(".detailInfo")[0]
            ele.style.display = "block"
        })
        cpuRef.value.addEventListener("mouseleave",() => {
            let ele:HTMLElement = document.querySelectorAll(".detailInfo")[0]
            ele.style.display = "none"
        })

        memRef.value.addEventListener("mouseenter",() => {
            let ele:HTMLElement = document.querySelectorAll(".detailInfo")[1]
            ele.style.display = "block"
        })
        memRef.value.addEventListener("mouseleave",() => {
            let ele:HTMLElement = document.querySelectorAll(".detailInfo")[1]
            ele.style.display = "none"
        })
        diskRef.value.addEventListener("mouseenter",() => {
            let ele:HTMLElement = document.querySelectorAll(".detailInfo")[2]
            ele.style.display = "block"
        })
        diskRef.value.addEventListener("mouseleave",() => {
            let ele:HTMLElement = document.querySelectorAll(".detailInfo")[2]
            ele.style.display = "none"
        })
    })
        // 离开界面停止渲染
        onUnmounted(() => {
        clearInterval(timer)
    })
    /**渲染系统函数 */
    const renderDisk = () => {
         diskUsage.value = systemInfo.value.diskInfo.diskUsage
        diskPirture.setOption(systemInfoPie(diskUsage.value))
    }
    const renderCpu = () => {
        cpuUsage.value = systemInfo.value.cpuInfo.cpuUsage
        platform.value = systemInfo.value.cpuInfo.platform
        cpuPirture.setOption(systemInfoPie(cpuUsage.value))
    }

    const renderMem = () => {
        memUsage.value = systemInfo.value.memInfo.freememPercentage
        freeMem.value = (Number(systemInfo.value.memInfo.freeMem)/1024).toFixed(2)
        totalMem.value = (Number(systemInfo.value.memInfo.totalMem)/1024).toFixed(2)
        leftMem.value = (totalMem.value - freeMem.value).toFixed(2)
        memPirture.setOption(systemInfoPie(memUsage.value))
    }

    // 定时渲染系统参数
    let timer = reactive<any>(null)
    if (localWebsocket.value) {
        timer = setInterval(() => {
            localWebsocket.value.send(JSON.stringify({action: "renderSystemInfo"}))
            renderCpu()
            renderMem()
        },2000)
    }

    // 修改系统的标题
    const changeSystemTitle = () => {
        // 保存到本地
        localStorage.setItem("system_title",system_title.value)
        document.title = system_title.value
        // 用户提醒
        proxy.notifySuccess(proxy.$t("setting.update_success"))
    }

    // 系统设置
    let system_set_user_dialog = ref(false)
    let system_set_Pass_dialog = ref(false)
    // 验证用户的身份
    const validateType = ref("")
    const validateUserCard = (type:string) => {
        validateType.value = type // 验证的类型
        validUserInfo.value = true
    }
    // 验证用户是否可以进行修改用户名
const validateUser = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error(proxy.$t("tip.empty_user")))
  } else if (!(/^[a-zA-Z0-9_-]{4,16}$/.test(value))) {
    callback(new Error(proxy.$t("tip.fail_user")))
  } else {
    callback()
  }
}
const confirmUpdateUser = () => {
    updateUserRef.value?.validate(async (res:any) => {
        if (!res) return proxy.$message({type:"info",message: proxy.$t("tip.user")})
        if (updateUsername.value.repeat_username === '') return proxy.$message({type: "info",message: proxy.$t("tip.empty_user")})
        if (updateUsername.value.repeat_username !== updateUsername.value.username) return proxy.$message({type: "warning",message: proxy.$t("tip.user_not_user")})
        // 判断是否开启远程监控，修改账号可能会导致使用错误
        if (user_store.deviceList.length !== 0) return proxy.$message({type: "info",message: proxy.$t("tip.close_remote")})
        let httpResult = await proxy.$outsideHttp.post("/user/updateUsername",{token: userInfo.value.token,username: updateUsername.value.username})
       if (httpResult.data.code !== 200) return proxy.$message({type: "error",message: proxy.$t("tip.update_user_fail")})
       // 提醒用户修改成功
       updateUsername.value.repeat_username = ""
       system_set_user_dialog.value = false
       proxy.$message({type:"success",message: proxy.$t("tip.update_user_success")})
       user_store.resetUsername(updateUsername.value.username,httpResult.data.data.newToken) 
    })
}
let updateUsername = ref({
    username: "",
    repeat_username: ""
})
 let updateUserRef = ref<FormInstance>()
  let updateUserRule = reactive<FormRules<any>>({
    username: [{ validator: validateUser, trigger: 'blur' }]
  })

  const resetUserInfo = () => {
    updateUserRef.value?.resetFields()
  }

    /**关于修改密码的代码 */
    const resetPassInfo = () => {
        updatePassRef.value?.resetFields()
    }

  let updateUserPass = ref<any>({
    password: "",
    repeat_password: ""
  })

// 验证密码
const validatePass = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error(proxy.$t('tip.empty_pass')))
  } else if (!(/^[a-zA-Z0-9]{6,12}$/.test(value))) {
    callback(new Error(proxy.$t('tip.fail_pass')))
  } else {
    callback()
  }
}
// 验证密码规则
let updatePassRule = reactive({
    password: [{ validator: validatePass, trigger: 'blur' }]
  })
  // 修改密码的实列
  let updatePassRef = ref()
  // {{$t("message.confirm")}}修改密码
  const confirmUpdatePass = () => {
    updatePassRef.value.validate(async (res:any) => {
        if (!res) return proxy.$message({type:"info",message: proxy.$t("tip.tip_pass")})
        if (updateUserPass.value.repeat_password === '') return proxy.$message({type:"info",message: proxy.$t('tip.empty_pass')})
        if (updateUserPass.value.repeat_password !== updateUserPass.value.password) return proxy.$message({type:"warning",message: proxy.$t("tip.pass_not_pass")})
        
        // 调用修改密码的api接口
       let httpResult = await proxy.$outsideHttp.post("/user/updatePassword",{token: userInfo.value.token,password: updateUserPass.value.password})
       if (httpResult.data.code !== 200) return proxy.$message({type: "error",message: proxy.$t("tip.update_pass_fail")})
       user_store.resetPassword(updateUserPass.value.password)
       // 提醒用户修改成功
       updateUserPass.value.repeat_password = ""
       system_set_Pass_dialog.value = false
       proxy.$message({type:"success",message: proxy.$t("tip.update_success")})
    })
  }

   /**绑定邮箱来找回密码*/
   let emailVisible = ref(false) //控制邮箱对话框显示
   let bindEmailModel = reactive({
        email: ""
   })

   const validateEmail = (rule: any, value: any, callback: any) => {
        if (value == '') {
            callback(new Error(proxy.$t("tip.tip_email")))
        } else if (!(/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(value))){
            callback(new Error(proxy.$t("tip.tip_email")))
        } else {
            callback()
        }
   }
   let bindEmailRef = ref() // 邮箱的实列对象
   let bindEmailRule = reactive({
        email: [{validator: validateEmail,trigger: "blur"}]
   })
   const resetEmail = () => {
     bindEmailRef.value.resetFields()
   }
   // 绑定邮箱
   const bindEmailFn = () => {
     emailVisible.value = true
   }
   // 解绑邮箱
   const unbindEmailFn = async () => {
      let result = await proxy.$outsideHttp.post("/user/unbindEmail",{token: userInfo.value.token})
        if (result.data.code !== 200) return proxy.$message({type:"error",message: proxy.$t("tip.unbind_email_fail")})
        user_store.resetEmail(bindEmailModel.email)
        proxy.$message({type: "success",message: proxy.$t("tip.unbind_email_success")})
   }
   const confirmBindEmail = () => {
    bindEmailRef.value.validate(async (res:any) => {
        if (!res) return proxy.$message({type:"warning",message: proxy.$t("tip.tip_email")})
        let result = await proxy.$outsideHttp.post("/user/bindEmail",{token: userInfo.value.token,email: bindEmailModel.email})
        if (result.data.code !== 200) return proxy.$message({type:"error",message: result.data.msg})
        user_store.bindEmail(bindEmailModel.email)
        emailVisible.value = false
        proxy.$message({type:"success",message: proxy.$t("tip.unbind_email_success")})
    })
   }
   // 打开系统文件
   const openFile = () => {
    //@ts-ignore
    systemApp.openDialog(systemInfo.value.diskInfo.currentPath)
   }

    /** 验证是否是管理员的用户，否则不能修改系统的用户名或者密码 */
   const validUserInfo = ref(false)
   const adminUser_pass = ref("")
   const handleClose = () => {
     adminUser_pass.value = ""
   }
   // 验证身份
   const validate_is_admin = () => {
     if (userInfo.value.password !== adminUser_pass.value) return proxy.$message({type:"error",message: proxy.$t('tip.valid_fail')})
     validUserInfo.value = false
     proxy.$message({type:"success",message: proxy.$t("tip.valid_success")})
        setTimeout(() => {
        // 审核通过进行下一步
        if (validateType.value == 'user') {
            updateUsername.value.username = userInfo.value.username
            system_set_user_dialog.value = true
        } else if(validateType.value == 'pass') {
            system_set_Pass_dialog.value = true
            updateUserPass.value.password = userInfo.value.password
        }
        },200)
   }
</script>

<style scoped lang="less">
        .system_status {
            height: 300px;
            width: 70%;
            padding: 0 20px;
            header {
                font-size: 20px;
                font-weight: 600;
                height: 60px;
                line-height: 60px;
                display: flex;
                align-items: center;
                &::before {
                    display: inline-block;
                    content: "";
                    width: 8px;
                    height: 32px;
                    background: #63b46b;
                    margin-right: 10px;
                }
            }
            main {
                padding: 10px;
                height: 240px;
                display: flex;
                aside {
                    height: 220px;
                    flex: 1;
                    position: relative;
                    .title {
                        position: absolute;
                        top: -5px;
                        width: 100%;
                        text-align: center;
                        font-size: 18px; 
                        color: #999999;
                    }
                    .desc {
                        position: absolute;
                        width: 100%;
                        height:30px;
                        text-align: center;
                        bottom: -10px;
                        color: #999;
                        font-size: 18px;
                        
                    }
                    .detailInfo {
                        position: absolute;
                        width: 400px;
                        border-radius: 10px;
                        background-color: #FFF;
                        z-index:9;
                        height: 300px;
                        left: 100px;
                        box-shadow: 0 0 6px #5a5a5a;
                        padding: 30px;
                        display: none;
                        .base_info {
                            height: 40px;
                            line-height: 40px;
                            padding-left: 3px;
                            background-color: #f9f9f9;
                        }
                        .aboutMem {
                            list-style: none;
                            display: grid;
                            height: 80px;
                            grid-template-rows: repeat(2,1fr);
                            grid-template-columns: repeat(2,1fr);
                            li {
                                display: flex;
                                justify-content: center;
                                align-items: center;
                            }
                        }
                    }
                    .system_chart {
                        width: 100%;
                        height: 100%;
                    }
                }
            }
}
.setting_parmas {
    padding: 0 20px;
    header {
        font-size: 20px;
        font-weight: 600;
        height: 60px;
        line-height: 60px;
        display: flex;
        align-items: center;
        &::before {
            display: inline-block;
            content: "";
            width: 8px;
            height: 32px;
            background: #63b46b;
            margin-right: 10px;
        }
    }
    main {
        width: 70%;
        padding-left: 40px;
        padding-top: 10px;
        section {
            display: flex;
            height: 50px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            .label {
                width: 150px;
                font-size: 18px;
                color: #555555;
                line-height: 50px;
                text-align: center;
            }
            .el-input {
                width: 300px;
                margin-right: 10px;
            }
            .el-button {
                margin-right:10px;
            }
            .desc {
                width: 40%;
                color: #999999;
            }
        }
    }
}
</style>